//LoginController.java
package org.example.demo3.controller;

import jakarta.servlet.http.HttpSession;
import org.example.demo3.service.AdminService;
import org.example.demo3.service.StudentService;
import org.example.demo3.service.TeacherService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class LoginController {
    @Autowired
    StudentService studentService;
    @Autowired
    TeacherService teacherService;
    @Autowired
    AdminService adminService;
    //登录验证
    @RequestMapping("loginValidate")
    public String loginValidate(int role,String username, String password, Model model, HttpSession session) {
        switch (role){
            case 1:
                //true：验证正确，跳转到StudentsList.html；false：验证错误，不跳转，停留在当前登录页
                if(adminService.login(username,password)){
                    //添加session有效的变量、令牌
                    session.setAttribute("username",username);
                    return "redirect:/Student/list/1/3";
                }else {
                    return "redirect:/login";
                }
            case 2:
                //true：验证正确，跳转到StudentsList.html；false：验证错误，不跳转，停留在当前登录页
                if(teacherService.login(username,password)){
                    //添加session有效的变量、令牌
                    session.setAttribute("username",username);
                    return "redirect:/Student/list/1/3";
                }else {
                    return "redirect:/login";
                }
            case 3:
                //true：验证正确，跳转到StudentsList.html；false：验证错误，不跳转，停留在当前登录页
                if(studentService.login(username,password)){
                    //添加session有效的变量、令牌
                    session.setAttribute("username",username);
                    return "redirect:/Student/list/1/3";
                }else {
                    return "redirect:/login";
                }
            default:
                return "redirect:/login";
        }

    }

    @RequestMapping("login")
    public String login(){
        return "login";
    }

    @RequestMapping("logout")
    public String logout(HttpSession session) {
        //让当前会话失效，同时回到登录页
        session.invalidate();
        return "redirect:/login";
    }
}
